<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="50vw"
    top="5vh"
    @close="handleClose"
  >
    <!-- 表单数据 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="98px"
      style="width: 44vw; margin-left: 50px"
    >
      <el-form-item :label="$t('table.icon')">
        <upload-logo
          @onSuccess="uploadIconSuccess"
          :logoUrl="form.icon ? `${$common.apiUrl + form.icon}` : null"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.name')" prop="name">
            <el-input
              :placeholder="$t('placeholder.Name')"
              v-model="form.name"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.url')" prop="url">
            <el-input
              :placeholder="$t('placeholder.Url')"
              v-model="form.url"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.gitee_url')" prop="gitee_url">
            <el-input
              v-model="form.gitee_url"
              :placeholder="$t('placeholder.GiteeUrl')"
          /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.github_url')" prop="github_url">
            <el-input
              v-model="form.github_url"
              :placeholder="$t('placeholder.GithubUrl')"
          /></el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.catalog_names')" prop="catalog_names">
            <el-select
              v-model="catalogs"
              filterable
              multiple
              tag-type="warning"
              :placeholder="$t('placeholder.Catalog')"
              @change="onChange($event, 'catalog_names')"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.sort_names')" prop="sort_names">
            <el-select
              v-model="sorts"
              filterable
              multiple
              tag-type="success"
              no-data-text="请先选择目录"
              :placeholder="$t('placeholder.Sort')"
              @change="onChange($event, 'sort_names')"
            >
              <el-option
                v-for="item in sortList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.tag_names')" prop="tag_names">
            <el-select
              v-model="tags"
              filterable
              multiple
              no-data-text="请先选择分类"
              :placeholder="$t('placeholder.Tag')"
              @change="onChange($event, 'tag_names')"
            >
              <el-option
                v-for="item in tagList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.is_pc')" prop="is_pc">
            <!-- @change="" -->
            <el-checkbox
              v-model="formBool.is_pc"
              @change="onChange($event, 'is_pc')"
            ></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.is_mobile')" prop="is_mobile">
            <!-- @change="" -->
            <el-checkbox
              v-model="formBool.is_mobile"
              @change="onChange($event, 'is_mobile')"
            ></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.is_download')" prop="is_download">
            <!-- @change="" -->
            <el-checkbox
              v-model="formBool.is_download"
              @change="onChange($event, 'is_download')"
            ></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.is_hot')" prop="is_hot">
            <!-- @change="" -->
            <el-checkbox
              v-model="formBool.is_hot"
              @change="onChange($event, 'is_hot')"
            ></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.is_vip')" prop="is_vip">
            <!-- @change="" -->
            <el-checkbox
              v-model="formBool.is_vip"
              @change="onChange($event, 'is_vip')"
            ></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.account')" prop="account">
            <el-input
              :placeholder="$t('placeholder.Account')"
              v-model="form.account"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.password')" prop="password">
            <el-input
              :placeholder="$t('placeholder.Password')"
              v-model="form.password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.vip_start')" prop="vip_start">
            <el-date-picker
              v-model="form.vip_start"
              type="date"
              :placeholder="$t('placeholder.Date')"
              :size="$store.getters.size"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.vip_end')" prop="vip_end">
            <el-date-picker
              v-model="form.vip_end"
              type="date"
              :placeholder="$t('placeholder.Date')"
              :size="$store.getters.size"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="$t('table.remark')" prop="remark">
            <el-input
              :placeholder="$t('placeholder.Remark')"
              v-model="form.remark"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('table.user_name')" prop="user_name">
            <el-input v-model="form.user_name" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('table.create_time')" prop="create_time">
            <el-input v-model="form.create_time" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 
      
      <el-row :gutter="20"></el-row> -->
    </el-form>
    <!-- 底部按钮组 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('dialog.Cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{
          $t('dialog.Confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import UploadLogo from '@/components/UploadLogo/index.vue' // 网站LOGO上传
import dayjs from 'dayjs'
import { addWebsite, updateWebsite } from '@/api/website.js'
import { getCatalogList } from '@/api/catalog.js'
import { getSortLsitByCatalogId } from '@/api/sort.js'
import { getTagLsitBySortId } from '@/api/tag.js'
import { useStore } from 'vuex'
const store = useStore()
import { useI18n } from 'vue-i18n'
const i18n = useI18n()

// 父组件传参
const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTableValue: {
    type: Object,
    default: () => {}
  }
})

// 是否显示弹窗
const dialogVisible = ref(false)
// 表单Ref
const formRef = ref(null)
// 表单数据
const form = ref({
  icon: null,
  name: null,
  url: null,
  gitee_url: null,
  github_url: null,
  catalog_ids: null,
  catalog_names: null,
  sort_ids: null,
  sort_names: null,
  tag_ids: null,
  tag_names: null,
  is_pc: 0,
  is_mobile: 0,
  is_download: 0,
  account: null,
  password: null,
  is_vip: 0,
  vip_start: null,
  vip_end: null,
  remark: '',
  user_id: null,
  user_name: null,
  create_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  is_hot: 0,
  is_delete: 0
})
// 用户信息
const userInfo = ref(store.getters.user || localStorage.getItem('user'))
// 目录选择
const catalogList = ref([]) // 源数据
const catalogs = ref([]) // 选择后数据
// 分类选择
const sortList = ref([]) // 源数据
const sorts = ref([]) // 选择后数据
// 标签选择
const tagList = ref([]) // 源数据
const tags = ref([]) // 选择后数据
// 布尔类型数据
const formBool = reactive({
  is_pc: false,
  is_mobile: false,
  is_download: false,
  is_vip: false,
  is_hot: false
})

// 表单校验
const rules = ref({
  name: [
    {
      required: true,
      message: i18n.t('rules.name'),
      trigger: 'blur'
    }
  ],
  url: [
    {
      required: true,
      message: i18n.t('rules.code'),
      trigger: 'blur'
    }
  ],
  catalog_names: [
    {
      required: true,
      message: i18n.t('rules.catalog'),
      trigger: 'blur'
    }
  ],
  sort_names: [
    {
      required: true,
      message: i18n.t('rules.sort'),
      trigger: 'blur'
    }
  ],
  tag_names: [
    {
      required: true,
      message: i18n.t('rules.tag'),
      trigger: 'blur'
    }
  ]
})

const emits = defineEmits(['update:modelValue', 'initWebsiteList'])

// 初始化数据
const initData = () => {
  form.value.user_id = userInfo.value.id
  form.value.user_name = userInfo.value.username
}

// 初始化目录
const initCatalogList = async () => {
  const res = await getCatalogList({
    page_num: 1,
    page_size: 10000
  })
  if (res.data.length > 0) {
    catalogList.value.length = 0
    res.data.map((item) => {
      catalogList.value.push({ value: item.id, label: item.name })
    })
  }
}
initCatalogList()

// 初始化分类
const initSortLsitByCatalogId = async (id) => {
  if (!id) {
    sortList.value.length = 0
    return
  }
  const res = await getSortLsitByCatalogId({ id })
  if (res.data.length > 0) {
    sortList.value.length = 0
    res.data.map((item) => {
      sortList.value.push({ value: item.id, label: item.name })
    })
  }
}

// 初始化标签
const initTagLsitBySortId = async (id) => {
  if (!id) {
    sortList.value.length = 0
    return
  }
  const res = await getTagLsitBySortId({ id })
  if (res.data.length > 0) {
    tagList.value.length = 0
    res.data.map((item) => {
      tagList.value.push({ value: item.id, label: item.name })
    })
  }
}

// 监听表单数据
watch(
  () => props.dialogTableValue,
  () => {
    if (props.dialogTitle === i18n.t('dialog.editData')) {
      const formData = JSON.parse(JSON.stringify(props.dialogTableValue))
      initSortLsitByCatalogId(formData.catalog_ids)
      initTagLsitBySortId(formData.sort_ids)
      catalogs.value = formData.catalog_ids.split(',').map((item) => item * 1)
      sorts.value = formData.sort_ids.split(',').map((item) => item * 1)
      tags.value = formData.tag_ids.split(',').map((item) => item * 1)
      formBool.is_pc = formData.is_pc === 1 ? true : false
      formBool.is_mobile = formData.is_mobile === 1 ? true : false
      formBool.is_download = formData.is_download === 1 ? true : false
      formBool.is_vip = formData.is_vip === 1 ? true : false
      formBool.is_hot = formData.is_hot === 1 ? true : false
      form.value = formData
    } else {
      initData()
    }
  },
  { deep: true, immediate: true }
)

// 关闭弹窗
const handleClose = () => {
  emits('update:modelValue', false)
}

// 确认
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log(form.value)
      const isEdit = props.dialogTitle === i18n.t('dialog.editData')
      const res = isEdit
        ? await updateWebsite(form.value)
        : await addWebsite(form.value)
      if (res.status === 0) {
        ElMessage.success(
          isEdit
            ? i18n.t('message.updeteSuccess')
            : i18n.t('message.saveSuccess')
        )
        emits('initWebsiteList')
        handleClose()
      } else {
        ElMessage.error(
          isEdit ? i18n.t('message.updeteFailed') : i18n.t('message.saveFailed')
        )
      }
    } else {
      return false
    }
  })
}

// 上传图标成功
const uploadIconSuccess = (data) => {
  form.value.icon = data.file_url
}

// 修改内容
const onChange = (event, type) => {
  // 选择目录
  if (type === 'catalog_names') {
    let catalog_names = ''
    event.map((item, index) => {
      let catalog = catalogList.value.find((ct) => ct.value === item)
      catalog_names =
        index === 0 ? catalog.label : catalog_names + ',' + catalog.label
    })
    form.value.catalog_names = catalog_names
    form.value.catalog_ids = event.toString()
    initSortLsitByCatalogId(event.toString())
    sorts.value.length = 0
    form.value.sort_ids = null
    form.value.sort_names = null
  }
  // 选择分类
  if (type === 'sort_names') {
    let sort_names = ''
    event.map((item, index) => {
      let sort = sortList.value.find((st) => st.value === item)
      sort_names = index === 0 ? sort.label : sort_names + ',' + sort.label
    })
    form.value.sort_names = sort_names
    form.value.sort_ids = event.toString()
    initTagLsitBySortId(event.toString())
    tags.value.length = 0
    form.value.tag_ids = null
    form.value.tag_names = null
  }
  // 选择标签
  if (type === 'tag_names') {
    let tag_names = ''
    event.map((item, index) => {
      let tag = tagList.value.find((st) => st.value === item)
      tag_names = index === 0 ? tag.label : tag_names + ',' + tag.label
    })
    form.value.tag_names = tag_names
    form.value.tag_ids = event.toString()
  }
  // 是否支持电脑
  if (type === 'is_pc') {
    form.value.is_pc = formBool.is_pc ? 1 : 0
  }
  // 是否支持手机
  if (type === 'is_mobile') {
    form.value.is_mobile = formBool.is_mobile ? 1 : 0
  }
  // 是否支持下载
  if (type === 'is_download') {
    form.value.is_download = formBool.is_download ? 1 : 0
  }
  // 是否热门网站
  if (type === 'is_hot') {
    form.value.is_hot = formBool.is_hot ? 1 : 0
  }
  // 是否开通会员
  if (type === 'is_vip') {
    form.value.is_vip = formBool.is_vip ? 1 : 0
  }
}
</script>
<style lang="scss" scoped>
::v-deep(.el-select) {
  width: 100% !important;
}
::v-deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  width: 100% !important;
}
</style>
